package com.hxl.linuxperformance;

import android.os.Bundle;
import android.os.Handler;
import android.util.Log;

import androidx.appcompat.app.AppCompatActivity;
import androidx.viewpager2.widget.ViewPager2;

import com.hxl.linuxperformance.adapter.ViewPagerAdapter;
import com.hxl.linuxperformance.entity.ComputerInfos;
import com.hxl.linuxperformance.network.Apis;
import com.hxl.linuxperformance.network.Url;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

public class MainActivity extends AppCompatActivity {
    private static final String TAG="MainActivity";
    private ViewPager2 mViewPager;
    private Retrofit mRetrofit;
    private Apis mApis;
    private Handler mHandler =new Handler();
    private Runnable mRequestRunnable;
    private  ViewPagerAdapter mViewPagerAdapter;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mViewPager =findViewById(R.id.viewpager);
        initRetrofit();
        mRequestRunnable =new RequestRunnable();

        mHandler.postDelayed(mRequestRunnable,0);
        mViewPagerAdapter =new ViewPagerAdapter(this);
        mViewPager.setAdapter(mViewPagerAdapter);
    }
    private  void initRetrofit(){
        mRetrofit= new Retrofit.Builder()
                .baseUrl(Url.HOST)
                .addConverterFactory(GsonConverterFactory.create())
                .build();
        mApis= mRetrofit.create(Apis.class);
    }
    private void addData(ComputerInfos computerInfos){
        mViewPagerAdapter.put(computerInfos);
    }
    class RequestRunnable implements Runnable{
        @Override
        public void run() {
            if (mHandler!=null && !isDestroyed()){
                Call<ComputerInfos> computerInfosCall = mApis.listInfos();
                computerInfosCall.enqueue(new Callback<ComputerInfos>() {
                    @Override
                    public void onResponse(Call<ComputerInfos> call, Response<ComputerInfos> response) {
                        addData(response.body());
                        Log.i(TAG, "onResponse: 请求");
                        mHandler.postDelayed(RequestRunnable.this,1000);
                    }

                    @Override
                    public void onFailure(Call<ComputerInfos> call, Throwable t) {
                        t.printStackTrace();
                        mHandler.postDelayed(RequestRunnable.this,1000);
                    }
                });

            }
        }
    }

}
